//
//  Socket+Extension.swift
//  HinsLive
//
//  Created by haoxian on 2019/5/9.
//  Copyright © 2019 Hins. All rights reserved.
//

import Foundation
import SocketIO


enum SocketEvent: String {
    case join
    case leave
    case message
    case alive
}


extension SocketIOClient {
    func on<T: NetworkModel>(event: SocketEvent, type: T.Type, _ callback: @escaping (T, SocketAckEmitter) -> Void) {
        on(event.rawValue) { (datas, ack) in
            guard let data = datas.first as? Data, let message = try? T(serializedData: data) else { return }
            callback(message, ack)
        }
    }
    
    func send(_ event: SocketEvent, _ message: NetworkModel) {
        guard let data = try? message.serializedData() else { return }
        emit(event.rawValue, data)
    }
}
